<?php
/**
 * User: 高振
 * Date: 14-4-3
 * Time: 下午4:48
 * Description：
 */
define('HTTP_SCHEME',isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on'?'https':'http');
define('DOMAIN_SUFFIX',substr(strstr($_SERVER['HTTP_HOST'],'.'),1));
define('SITE_URL','http://'.strip_tags($_SERVER['HTTP_HOST']));
define('IS_WIN',strstr(PHP_OS, 'WIN') ? 1 : 0 );

//session_start();
define('ROOT_PATH', dirname(__FILE__));

error_reporting(E_ERROR | E_WARNING | E_PARSE);
spl_autoload_register("loadLib");

session(C('SESSION_OPTIONS'));

//异常处理机制
set_exception_handler(function($exception){
    $errorCode = $exception->getCode();
    $errorMsg = $exception->getMessage();
    if($errorMsg=='No route to host')
    {
        $errorCode = 1000;
    }
    json_exit(array('info'=>$errorMsg,'status'=>(String)$errorCode,));
});

/**
 * @param $className
 */
function loadLib($className)
{
    $filepath = dirname(__FILE__)."/Lib/".$className . '.class.php';
    if (file_exists($filepath))
    {
        require_once($filepath);
    }
    else
    {
        die("no found file: ".$filepath);
    }
}


function C($name=null, $value=null,$default=null) {
    static $_config = array();

    if(empty($_config)){
        $_config = require_once "Config/Config.php";
    }

    // 无参数时获取所有
    if (empty($name)) {
        return $_config;
    }
    // 优先执行设置获取或赋值
    if (is_string($name)) {
        if (!strpos($name, '.')) {
            $name = strtoupper($name);
            if (is_null($value))
                return isset($_config[$name]) ? $_config[$name] : $default;
            $_config[$name] = $value;
            return null;
        }
        // 二维数组设置和获取支持
        $name = explode('.', $name);
        $name[0]   =  strtoupper($name[0]);
        if (is_null($value))
            return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : $default;
        $_config[$name[0]][$name[1]] = $value;
        return null;
    }
    // 批量设置
    if (is_array($name)){
        $_config = array_merge($_config, array_change_key_case($name,CASE_UPPER));
        return null;
    }
    return null; // 避免非法参数
}

/**
 * 缓存方法
 * @param $key
 * @param string $value
 * @param int $expire
 * @return mixed
 */
function cache($key,$value=''){
    if(empty($key)) return false;



    if($value){
        $data    = "<?php\n return ".var_export($value,true)  . "\n?>";
        $fileName = ROOT_PATH.'/Config/'.$key.'.php';
        file_put_contents($fileName,$data);
    } else {
        static $includeCache = array();
        $fileName = ROOT_PATH.'/Config/'.$key.'.php';

        if(file_exists($fileName)){
            if(!$includeCache[md5($fileName)]){
                $includeCache[md5($fileName)] = require_once $fileName;
            }
            return $includeCache[md5($fileName)];
        } else {
            return false;
        }
    }
}

/**
 * 获取附件配置
 * @param $alias 配置别名
 * @param string $uid 用户ID
 * @return mixed
 */
function get_attach($alias,$uid='',$role=1)
{
    $_attachList = cache('attach');
    if(empty($_attachList)){
        throw new Exception('附件配置文件不存在');
    } else {
        $_attach = $_attachList[$alias];
        if(empty($_attach)){
            throw new Exception('不存在此附件配置');
        }

        $attach_root_path = rtrim(ROOT_PATH,'/').'/' . trim(C('ATTACH_DIR'),'/').'/';

        if($uid > 0){
            $spaceDir = 'User';
            $root_dir_path = $attach_root_path.$spaceDir.'/' . $uid .'/'.trim($_attach['dir_path'],'/').'/'.ceil($uid/30000) .'/';
            $root_img_path = rtrim(C("TMPL_PARSE_STRING.__IMG__"),'/').'/'.$spaceDir.'/'.$uid.'/'.trim($_attach['dir_path'],'/').'/'.ceil($uid/30000) .'/';
        } else {
            $root_dir_path = $attach_root_path.'Admin/'.trim($_attach['dir_path'],'/').'/';
            $root_img_path = rtrim(C("TMPL_PARSE_STRING.__IMG__"),'/').'/Admin/'.trim($_attach['dir_path'],'/').'/';
        }

        if (!file_exists($root_dir_path))
        {
            mk_dir($root_dir_path);
        }

        $_attach['dir_path'] = $root_dir_path;
        $_attach['img_root'] = $root_img_path;
    }
    return $_attach;
}

// 循环创建目录
function mk_dir($dir, $mode = 0777)
{
    if (is_dir($dir) || @mkdir($dir, $mode)){
        return true;
    }

    if (!mk_dir(dirname($dir), $mode))
        return false;
    return @mkdir($dir, $mode);
}

/**
 * @param $msg
 * @param string $callback
 */
function json_exit($msg,$callback='',$dataType='json')
{
    switch (strtoupper($dataType)){
        case 'JSON' :
            // 返回JSON数据格式到客户端 包含状态信息
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode($msg,JSON_UNESCAPED_UNICODE));
        case 'XML'  :
            // 返回xml格式数据
            header('Content-Type:text/xml; charset=utf-8');
            exit(xml_encode($msg));
        case 'JSONP':
            // 返回JSON数据格式到客户端 包含状态信息
            header('Content-Type:application/json; charset=utf-8');
            $handler  =   $callback?$callback:'jsonpReturn';
            exit($handler.'('.json_encode($msg,JSON_UNESCAPED_UNICODE).');');
        case 'EVAL' :
            // 返回可执行的js脚本
            header('Content-Type:text/html; charset=utf-8');
            exit($msg);
    }
}

/**
 * debug
 */
function debug()
{
    print_r(func_get_args());
    die;
}

/**
 * @param $fullpath
 * @return mixed
 */
function getFileName($fullpath)
{
    $tmpArr = explode('/',$fullpath);
    return $picname = $tmpArr[count($tmpArr)-1];
}

/**
 * @param $var
 * @param $array
 * @return bool
 */
function _in_array($var,$array)
{
    foreach($array as $v)
    {
        if($var == $v)
        {
            return true;
        }
    }
}


/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-6-13
 * Time: 下午1:57
 * 获取签名
 */
function get_signature($str, $key)
{
    $signature = "";
    if (function_exists('hash_hmac'))
    {
        $signature = base64_encode(hash_hmac("sha1", $str, $key, true));
    }
    else
    {
        $blocksize	= 64;
        $hashfunc	= 'sha1';
        if (strlen($key) > $blocksize)
        {
            $key = pack('H*', $hashfunc($key));
        }
        $key	= str_pad($key,$blocksize,chr(0x00));
        $ipad	= str_repeat(chr(0x36),$blocksize);
        $opad	= str_repeat(chr(0x5c),$blocksize);
        $hmac 	= pack(
            'H*',$hashfunc(
                ($key^$opad).pack(
                    'H*',$hashfunc(
                        ($key^$ipad).$str
                    )
                )
            )
        );
        $signature = base64_encode($hmac);
    }
    return $signature;
}

/**
 * @return string
 * URL及参数处理
 */
function params_deal($host,$params=null){
    if($params==null) $params = $_REQUEST;
    $array = $params;
    unset($array['sig']);
    ksort($array);
    require_once ROOT_PATH.'/Lib/HttpClient.class.php';
    $host =  OAuthUtil::urlencode_rfc3986($host);
    $key = $host.'&'.OAuthUtil::build_http_query($array);
    return $key;
}

/**
 * @param $akey
 * @param $skey
 * @return string
 * 获取密钥
 */
function get_secret($akey,$skey){
    return md5($akey).md5($skey).md5($akey.$skey);
}

function session($name='',$value='') {
    $prefix   =  C('SESSION_PREFIX');
    if(is_array($name)) { // session初始化 在session_start 之前调用
        if(isset($name['prefix'])) C('SESSION_PREFIX',$name['prefix']);
        if(C('VAR_SESSION_ID') && isset($_REQUEST[C('VAR_SESSION_ID')])){
            session_id($_REQUEST[C('VAR_SESSION_ID')]);
        }elseif(isset($name['id'])) {
            session_id($name['id']);
        }
        ini_set('session.auto_start', 0);
        if(isset($name['name']))            session_name($name['name']);
        if(isset($name['path']))            session_save_path($name['path']);
        if(isset($name['domain']))          ini_set('session.cookie_domain', $name['domain']);
        if(isset($name['expire']))          {
            ini_set('session.gc_maxlifetime',   $name['expire']);
            ini_set('session.cookie_lifetime',  $name['expire']);
        }
        if(isset($name['use_trans_sid']))   ini_set('session.use_trans_sid', $name['use_trans_sid']?1:0);
        if(isset($name['use_cookies']))     ini_set('session.use_cookies', $name['use_cookies']?1:0);
        if(isset($name['cache_limiter']))   session_cache_limiter($name['cache_limiter']);
        if(isset($name['cache_expire']))    session_cache_expire($name['cache_expire']);
        if(isset($name['type']))            C('SESSION_TYPE',$name['type']);
        if(C('SESSION_TYPE')) { // 读取session驱动
            $type   =   C('SESSION_TYPE');
            $hander =   new $type();
            session_set_save_handler(
                array(&$hander,"open"),
                array(&$hander,"close"),
                array(&$hander,"read"),
                array(&$hander,"write"),
                array(&$hander,"destroy"),
                array(&$hander,"gc"));
        }
        // 启动session
        if(C('SESSION_AUTO_START'))  session_start();
    }elseif('' === $value){
        if(''===$name){
            // 获取全部的session
            return $prefix ? $_SESSION[$prefix] : $_SESSION;
        }elseif(0===strpos($name,'[')) { // session 操作
            if('[pause]'==$name){ // 暂停session
                session_write_close();
            }elseif('[start]'==$name){ // 启动session
                session_start();
            }elseif('[destroy]'==$name){ // 销毁session
                $_SESSION =  array();
                session_unset();
                session_destroy();
            }elseif('[regenerate]'==$name){ // 重新生成id
                session_regenerate_id();
            }
        }elseif(0===strpos($name,'?')){ // 检查session
            $name   =  substr($name,1);
            if(strpos($name,'.')){ // 支持数组
                list($name1,$name2) =   explode('.',$name);
                return $prefix?isset($_SESSION[$prefix][$name1][$name2]):isset($_SESSION[$name1][$name2]);
            }else{
                return $prefix?isset($_SESSION[$prefix][$name]):isset($_SESSION[$name]);
            }
        }elseif(is_null($name)){ // 清空session
            if($prefix) {
                unset($_SESSION[$prefix]);
            }else{
                $_SESSION = array();
            }
        }elseif($prefix){ // 获取session
            if(strpos($name,'.')){
                list($name1,$name2) =   explode('.',$name);
                return isset($_SESSION[$prefix][$name1][$name2])?$_SESSION[$prefix][$name1][$name2]:null;
            }else{
                return isset($_SESSION[$prefix][$name])?$_SESSION[$prefix][$name]:null;
            }
        }else{
            if(strpos($name,'.')){
                list($name1,$name2) =   explode('.',$name);
                return isset($_SESSION[$name1][$name2])?$_SESSION[$name1][$name2]:null;
            }else{
                return isset($_SESSION[$name])?$_SESSION[$name]:null;
            }
        }
    }elseif(is_null($value)){ // 删除session
        if(strpos($name,'.')){
            list($name1,$name2) =   explode('.',$name);
            if($prefix){
                unset($_SESSION[$prefix][$name1][$name2]);
            }else{
                unset($_SESSION[$name1][$name2]);
            }
        }else{
            if($prefix){
                unset($_SESSION[$prefix][$name]);
            }else{
                unset($_SESSION[$name]);
            }
        }
    }else{ // 设置session
        if(strpos($name,'.')){
            list($name1,$name2) =   explode('.',$name);
            if($prefix){
                $_SESSION[$prefix][$name1][$name2]   =  $value;
            }else{
                $_SESSION[$name1][$name2]  =  $value;
            }
        }else{
            if($prefix){
                $_SESSION[$prefix][$name]   =  $value;
            }else{
                $_SESSION[$name]  =  $value;
            }
        }
    }
    return null;
}